<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Faker\Provider\DateTime;
use App\Good;
use App\User;
use Illuminate\Support\Facades\Cache;
use Carbon\Carbon;
use EasyWeChat\OfficialAccount\Server\Guard;

class UserController extends Controller
{
    protected $http;

    public function __construct(\GuzzleHttp\Client $http)
    {
        $this->http = $http;
    }

    // 获取缓存
    private function get_token_value($token){

        $json_str = Cache::get($token);
        $res = json_decode($json_str,false);
        return $res;

    }

    // 我的发布
    public function my_houses(Request $request){

        $user = \Auth::guard('wechat')->user();
        $houses = $user->houses()->orderBy('created_at',"desc")->paginate(5);
        return $this->modify($houses);

    }

    // 我的关注
    public function my_likes(Request $request){

        $user = \Auth::guard('wechat')->user();
        $houses = $user->liked_houses()->orderBy("created_at","desc")->paginate(6);
        return $this->modify($houses);

    }

    // 修改数据格式
    private function modify($houses){
        foreach($houses as $k=>$house){
            $houses[$k]["coverurl"]= $this->getCoverImg($house["imgs"]);
            unset($houses[$k]["imgs"]);
        }
        return $houses;
    }


     //获取封面图片;
     private  function getCoverImg($str){
        $imgArr = explode("&", $str);
        return config('app.upload').'s_'.$imgArr[0]; // 默认第一张图片为封面图片;
    }


    // 获取登录用户信息
    public function user(Request $request){

         // 1 获取登录用户;
         $user = \Auth::guard('wechat')->user();
         return $user;

    }


    public function order(Request $request){
        $token= $request->header("token");
        if(Cache::has($token)){
            return "ok";
        }else{
            return "false";
        }
    }

    //请求商品品类列表;
    public function getTypes(){
        $data = DB::table('categories')
            ->select(DB::raw('*,concat(path,",",id) npath'))
            ->orderBy('npath','asc')
            ->get();
        return $data;
    }

    // 获取品类下的商品
    public function goods($id){
         $data = Good::where("category_id",$id)->get();
         return $data;
    }

    // 接收小程序code
    public  function token(Request $request){

        $params = $request->user;
      

        // 1 获取open_id  appscreat_key;

        $code = $request->code;
        $appid = config('app.appid');
        $appsecret = config('app.appsecret');
        $url= config('app.code2session');

        $wxurl = sprintf($url,$appid,$appsecret,$code);


        // 1  向微信服务器发起请求 通过code 换取session_key 与openid

        // $res = $this->http->get($wxurl);
        // $res = file_get_contents($wxurl);

        $res = $this->curl_get($wxurl);

        
        // {session_key: "mt3d0rfsuSbLiZoOxbOAug==", openid: "oDesE5pVeptkOZ21TJe78V6CJSAo"}

        // 将json字符串转换为php变量,true数组 false对象;
       // $wxResult = json_decode($res,true);

        // 2 生成令牌(随机唯一字符串)
       $token = $this->getToken();

      // $token = uniqid();
      // $token = session_create_id();  // php7.1 

       // 3 获取openid
       $openid = $res->openid;

       // 4 通过openid  去微信用户表中查询(存在返回记录，不存则追加);
        $user = User::updateOrCreate(
            
            ['openid' => $openid],
            [ "nick_name"=>$params['nickName'],
            "city"=>$params['city'],
            "gender"=>$params['gender'],
            "avatar_url"=>$params['avatarUrl'],
            "api_token"=>$token]);
            
        if(!$user){
             return response()->json(["status"=>"3000"]);
        }

        // 5 往缓存中存储数据
        // $res = {session_key: "mt3d0rfsuSbLiZoOxbOAug==", openid: "oDesE5pVeptkOZ21TJe78V6CJSAo",uid:33}

        $res->uid = $user->id;
        $res->user = json_encode($user);

        $expire_in = Carbon::now()->addDays(30);     // 有效期30天;
       // $expire = Carbon::now()->addMinute(1);     // 有效期1分钟;

        // 把php对象转换为json字符串;
        $json_str = json_encode($res);

        Cache::put($token,$json_str,$expire_in);

        //$res = Cache::get($token); //缓存中获取token;

        // 6 把$token返回给客户端;
        //return response()->json(["token"=>$token,"uid"=>$user->id]);

        return response()->json([
            'token' => $token,
            'expires_in' => $expire_in,
            'user' => $user,
            'uid' => $user->id
        ],200);
        
    }


    // 生成令牌
    private function getToken(){
        $random = $this->getRandChar(32);
        $time =  time();
        $salt = config("app.token_salt");
        $token_str = $random.$time.$salt;
        $token = md5($token_str);
        return $token;
    }3

    // 生成随机字符串
    private function getRandChar($length)
    {
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol) - 1;

        for ($i = 0; $i < $length; $i++) {
            $str .= $strPol[rand(0, $max)];
        }
        return $str;
    }

    // php 原生模拟发起get请求

    private function curl_get($url){

    $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //设置为不是https也可以访问
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST,0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER,0);

        $result = curl_exec($ch);
        curl_close($ch);
        $ret = json_decode($result);
        return $ret;
    }


}
